package top.ochiamalu.aioj.config;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.ochiamalu.aioj.constant.DisruptorConstants;
import top.ochiamalu.aioj.disruptor.JudgeEvent;
import top.ochiamalu.aioj.disruptor.JudgeEventHandler;

import java.util.concurrent.Executors;

/**
 * Disruptor配置
 *
 * @author ochiamalu
 * @date 2025/01/23
 */
@Configuration
public class DisruptorConfig {

    @Bean
    public RingBuffer<JudgeEvent> ringBuffer(JudgeEventHandler handler) {
        // 指定RingBuffer大小
        int bufferSize = DisruptorConstants.DEFAULT_BUFFER_SIZE;

        // 创建disruptor
        Disruptor<JudgeEvent> disruptor = new Disruptor<>(
                JudgeEvent::new,
                bufferSize,
                Executors.defaultThreadFactory()
        );

        // 连接handler
        disruptor.handleEventsWith(handler);

        // 启动disruptor
        disruptor.start();

        // 返回RingBuffer
        return disruptor.getRingBuffer();
    }
}
